{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-07-15T05:33:26.958721Z",
     "start_time": "2025-07-15T05:33:18.847413Z"
    }
   },
   "source": [
    "\n",
    "from langchain.chat_models import init_chat_model\n",
    "from langchain_core.messages import HumanMessage\n",
    "\n",
    "# 初始化模型，指定 base_url 为 DashScope 的 OpenAI 兼容接口地址\n",
    "model = init_chat_model(\n",
    "    \"glm-4-flash-250414\",  # 可替换为你想使用的 DashScope 模型，如 qwen-plus、qwen-turbo 等\n",
    "    model_provider=\"openai\",\n",
    "    base_url=\"https://open.bigmodel.cn/api/paas/v4/\",\n",
    "    openai_api_key=\"f1083622e2424058bfb7cdf7e48a7fb4.XxRmRC4VFmbNjz0K\"\n",
    ")\n",
    "\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.graph import START, MessagesState, StateGraph\n",
    "\n",
    "# Define a new graph\n",
    "workflow = StateGraph(state_schema=MessagesState)\n",
    "\n",
    "\n",
    "# Define the function that calls the model\n",
    "def call_model(state: MessagesState):\n",
    "    response = model.invoke(state[\"messages\"])\n",
    "    return {\"messages\": response}\n",
    "\n",
    "\n",
    "# Define the (single) node in the graph\n",
    "workflow.add_edge(START, \"model\")\n",
    "workflow.add_node(\"model\", call_model)\n",
    "\n",
    "# Add memory\n",
    "memory = MemorySaver()\n",
    "app = workflow.compile(checkpointer=memory)\n",
    "\n",
    "config = {\"configurable\": {\"thread_id\": \"abc123\"}}\n",
    "query = \"Hi! I'm Bob.\"\n",
    "\n",
    "input_messages = [HumanMessage(query)]\n",
    "output = app.invoke({\"messages\": input_messages}, config)\n",
    "output[\"messages\"][-1].pretty_print()  # output contains all messages in state"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001B[1m Ai Message \u001B[0m==================================\n",
      "\n",
      "Hi Bob! Nice to meet you. 😊 How can I help you today?\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-15T05:33:27.439677Z",
     "start_time": "2025-07-15T05:33:27.376082Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "prompt_template = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\n",
    "            \"system\",\n",
    "            \"You are a helpful assistant. Answer all questions to the best of your ability in {language}.\",\n",
    "        ),\n",
    "        MessagesPlaceholder(variable_name=\"messages\"),\n",
    "    ]\n",
    ")"
   ],
   "id": "7d0a466f18c5d34e",
   "outputs": [],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-15T05:33:27.463242Z",
     "start_time": "2025-07-15T05:33:27.456086Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from typing import Sequence\n",
    "\n",
    "from langchain_core.messages import BaseMessage\n",
    "from langgraph.graph.message import add_messages\n",
    "from typing_extensions import Annotated, TypedDict\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[Sequence[BaseMessage], add_messages]\n",
    "    language: str\n",
    "\n",
    "\n",
    "workflow = StateGraph(state_schema=State)\n",
    "\n",
    "\n",
    "def call_model(state: State):\n",
    "    prompt = prompt_template.invoke(state)\n",
    "    response = model.invoke(prompt)\n",
    "    return {\"messages\": [response]}\n",
    "\n",
    "\n",
    "workflow.add_edge(START, \"model\")\n",
    "workflow.add_node(\"model\", call_model)\n",
    "\n",
    "memory = MemorySaver()\n",
    "app = workflow.compile(checkpointer=memory)"
   ],
   "id": "e8fb60c16794c981",
   "outputs": [],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-15T05:33:50.874732Z",
     "start_time": "2025-07-15T05:33:49.345385Z"
    }
   },
   "cell_type": "code",
   "source": [
    "config = {\"configurable\": {\"thread_id\": \"abc456\"}}\n",
    "query = \"Hi! I'm Bob.\"\n",
    "language = \"Chinese\"\n",
    "\n",
    "input_messages = [HumanMessage(query)]\n",
    "output = app.invoke(\n",
    "    {\"messages\": input_messages, \"language\": language},\n",
    "    config,\n",
    ")\n",
    "output[\"messages\"][-1].pretty_print()"
   ],
   "id": "e5a0e017836137e2",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001B[1m Ai Message \u001B[0m==================================\n",
      "\n",
      "你好，Bob！很高兴认识你。有什么我可以帮助你的吗？\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-15T05:34:26.027722Z",
     "start_time": "2025-07-15T05:34:25.629135Z"
    }
   },
   "cell_type": "code",
   "source": [
    "query = \"What is my name?\"\n",
    "\n",
    "input_messages = [HumanMessage(query)]\n",
    "output = app.invoke(\n",
    "    {\"messages\": input_messages},\n",
    "    config,\n",
    ")\n",
    "output[\"messages\"][-1].pretty_print()"
   ],
   "id": "d37de2ae87eac901",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001B[1m Ai Message \u001B[0m==================================\n",
      "\n",
      "你的名字是Bob。\n"
     ]
    }
   ],
   "execution_count": 6
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
